import React, { useState } from 'react';
import {
  Box,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  TextField,
  Typography,
  useTheme,
  useMediaQuery,
  Alert,
  Snackbar,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
} from '@mui/material';
import axios from 'axios';

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001/api';

interface User {
  _id?: string;
  id?: string;
  username: string;
  email: string;
  role?: 'admin' | 'user';
}

interface UserProfileEditProps {
  user: User;
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
  isAdmin?: boolean;
}

const UserProfileEdit: React.FC<UserProfileEditProps> = ({
  user,
  open,
  onClose,
  onSuccess,
  isAdmin = false,
}) => {
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setSuccess(false);

    // 验证新密码
    if (newPassword && newPassword !== confirmPassword) {
      setError('两次输入的新密码不一致');
      return;
    }

    if (newPassword && newPassword.length < 6) {
      setError('新密码长度不能少于6个字符');
      return;
    }

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        setError('未登录或登录已过期');
        return;
      }

      const headers = { Authorization: `Bearer ${token}` };
      const data: any = {};

      // 如果是管理员修改其他用户的密码，不需要当前密码
      if (!isAdmin) {
        if (!currentPassword) {
          setError('请输入当前密码');
          return;
        }
        data.currentPassword = currentPassword;
      }

      if (newPassword) {
        data.newPassword = newPassword;
      }

      // 使用正确的用户ID
      const userId = user._id || user.id;
      if (!userId) {
        console.error('用户ID不存在:', user);
        setError('用户ID不存在');
        return;
      }

      console.log('正在更新用户信息:', {
        userId,
        isAdmin,
        hasCurrentPassword: !!data.currentPassword,
        hasNewPassword: !!data.newPassword
      });

      // 根据是否是管理员使用不同的 API 路径
      const apiPath = isAdmin 
        ? `${API_URL}/auth/users/${userId}/password`
        : `${API_URL}/auth/users/me/password`;

      console.log('API 路径:', apiPath);
      console.log('请求数据:', data);

      await axios.put(
        apiPath,
        data,
        { headers }
      );

      setSuccess(true);
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
      
      // 延迟关闭对话框，让用户看到成功消息
      setTimeout(() => {
        onSuccess();
        onClose();
      }, 1500);
    } catch (error: any) {
      console.error('更新用户信息失败:', error);
      setError(error.response?.data?.message || '更新用户信息失败');
    }
  };

  return (
    <Dialog 
      open={open} 
      onClose={onClose}
      maxWidth="sm"
      fullWidth
      PaperProps={{
        sx: {
          m: isMobile ? 1 : 2,
          width: isMobile ? 'calc(100% - 16px)' : 'auto'
        }
      }}
    >
      <DialogTitle sx={{ pb: 1 }}>
        {isAdmin ? '修改用户密码' : '修改密码'}
      </DialogTitle>
      <form onSubmit={handleSubmit}>
        <DialogContent sx={{ pb: 2 }}>
          {error && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {error}
            </Alert>
          )}
          {success && (
            <Alert severity="success" sx={{ mb: 2 }}>
              更新成功
            </Alert>
          )}
          <Box sx={{ mb: 2 }}>
            <Typography variant="body2" color="textSecondary" gutterBottom>
              用户名: {user.username}
            </Typography>
            <Typography variant="body2" color="textSecondary">
              邮箱: {user.email}
            </Typography>
          </Box>
          {!isAdmin && (
            <TextField
              fullWidth
              label="当前密码"
              type="password"
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
              margin="normal"
              required
              size={isMobile ? "small" : "medium"}
            />
          )}
          <TextField
            fullWidth
            label="新密码"
            type="password"
            value={newPassword}
            onChange={(e) => setNewPassword(e.target.value)}
            margin="normal"
            required
            size={isMobile ? "small" : "medium"}
          />
          <TextField
            fullWidth
            label="确认新密码"
            type="password"
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
            margin="normal"
            required
            size={isMobile ? "small" : "medium"}
          />
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2 }}>
          <Button onClick={onClose} size={isMobile ? "small" : "medium"}>
            取消
          </Button>
          <Button 
            type="submit" 
            variant="contained" 
            color="primary"
            size={isMobile ? "small" : "medium"}
          >
            保存
          </Button>
        </DialogActions>
      </form>
    </Dialog>
  );
};

export default UserProfileEdit; 